<?php

namespace app\api\controller\admin;

use app\admin\model\dts\approve\daily\Let as dailyLet;
use app\admin\model\dts\approve\expen\Let as expenLet;
use app\admin\model\dts\approve\food\Let as foodLet;
use app\common\controller\TApi;
use think\Db;

/**
 * 物资接口
 */
class Material extends TApi
{
    protected $noNeedRight = ['*'];
    protected $categoryArr = ['daily', 'expen', 'food'];

    //日常物资列表
    public function dailyMaterialList() {

        $type = intval($this->request->get('type', 0));
        $categoryname = $this->request->get('categoryname');
        $materialname = $this->request->get('materialname');
        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);

        $list = []; $query = [];
        $admin = $this->auth->getAdmininfo();

        if(!$type) {
            $query = $categoryname ? ['dmc.name' => ['LIKE', '%' . $categoryname . '%']] : [];
                
            $list = Db::name('dts_material_category')->alias('dmc')
            ->field('dmc.id,dmc.name,dmd.images,COUNT(dmd.id) as quantity')
            ->join('dts_material_daily dmd', 'dmd.material_category_id = dmc.id', 'left')
            ->where($query)
            ->where('dmc.category', 'daily')
            ->group('dmc.id')
            ->paginate($pagesize, false, ['page' => $page]);
        }else {
            $letIds = Db::name('dts_approve_daily_let')->where(['admin_id' => $admin['id'], 'status' => dailyLet::status_5])->column('id');
            if($letIds) {
                $query = $materialname ? ['dmd.name' => ['LIKE', '%' . $materialname . '%']] : [];

                $list = Db::name('dts_approve_daily_log')->alias('dadl')
                ->field('dmd.id,dmd.name,dmd.images,dmd.unity,dmd.specs,SUM(dadl.quantity) as quantity')
                ->join('dts_material_daily dmd', 'dmd.id = dadl.material_daily_id', 'left')
                ->where('dadl.daily_let_id', 'in', $letIds)
                ->where($query)
                ->group('dadl.material_daily_id')
                ->paginate($pagesize, false, ['page' => $page]);
            }
        }

        $this->success('success', $list);
    }

    //易耗物资列表
    public function expenMaterialList() {

        $type = intval($this->request->get('type', 0));
        $categoryname = $this->request->get('categoryname');
        $materialname = $this->request->get('materialname');
        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);

        $list = []; $query = [];
        $admin = $this->auth->getAdmininfo();

        if(!$type) {
            $query = $categoryname ? ['dmc.name' => ['LIKE', '%' . $categoryname . '%']] : [];

            $list = Db::name('dts_material_category')->alias('dmc')
            ->field('dmc.id,dmc.name,COUNT(dme.id) as quantity')
            ->join('dts_material_expen dme', 'dme.material_category_id = dmc.id', 'left')
            ->where($query)
            ->where('dmc.category', 'expen')
            ->group('dmc.id')
            ->paginate($pagesize, false, ['page' => $page]);
        }else {
            $letIds = Db::name('dts_approve_expen_let')->where(['admin_id' => $admin['id'], 'status' => expenLet::status_5])->column('id');
            if($letIds) {
                $query = $materialname ? ['dme.name' => ['LIKE', '%' . $materialname . '%']] : [];

                $list = Db::name('dts_approve_expen_log')->alias('dael')
                ->field('dme.id,dme.name,dme.unity,dme.specs,SUM(dael.quantity) as quantity')
                ->join('dts_material_expen dme', 'dme.id = dael.material_expen_id', 'left')
                ->where('dael.expen_let_id', 'in', $letIds)
                ->where($query)
                ->group('dael.material_expen_id')
                ->paginate($pagesize, false, ['page' => $page]);
            }
        }

        $this->success('success', $list);
    }

    //食材物资列表
    public function foodMaterialList() {

        $type = intval($this->request->get('type', 0));
        $categoryname = $this->request->get('categoryname');
        $materialname = $this->request->get('materialname');
        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);

        $list = []; $query = [];
        $admin = $this->auth->getAdmininfo();

        if(!$type) {
            $query = $categoryname ? ['dmc.name' => ['LIKE', '%' . $categoryname . '%']] : [];

            $list = Db::name('dts_material_category')->alias('dmc')
            ->field('dmc.id,dmc.name,COUNT(dmf.id) as quantity')
            ->join('dts_material_food dmf', 'dmf.material_category_id = dmc.id', 'left')
            ->where($query)
            ->where('dmc.category', 'food')
            ->group('dmc.id')
            ->paginate($pagesize, false, ['page' => $page]);
        }else {
            $letIds = Db::name('dts_approve_food_let')->where(['admin_id' => $admin['id'], 'status' => foodLet::status_5])->column('id');
            if($letIds) {
                $query = $materialname ? ['dmf.name' => ['LIKE', '%' . $materialname . '%']] : [];

                $list = Db::name('dts_approve_food_log')->alias('dafl')
                ->field('dmf.id,dmf.name,dmf.unity,dmf.specs,SUM(dafl.quantity) as quantity')
                ->join('dts_material_food dmf', 'dmf.id = dafl.material_food_id', 'left')
                ->where('dafl.food_let_id', 'in', $letIds)
                ->where($query)
                ->group('dafl.material_food_id')
                ->paginate($pagesize, false, ['page' => $page]);
            }
        }

        $this->success('success', $list);
    }


    //物资分类详情
    public function categoryDetails() {

        $id = $this->request->get('id');
        $category = $this->request->get('category');
        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);
        if(!$id || !$category) {
            $this->error('请填选择查询物资分类');
        }
        if(!in_array($category, $this->categoryArr)) {
            $this->error('物资类型参数有误');
        }

        $name = $this->request->get('name');
        $query = $name ? ['name' => ['LIKE', '%'.$name.'%']] : [];

        $field = 'id,name,unity,specs,quantity,consume';
        if($category == 'daily') {
            $field = $field . ',images';
        }

        $list = Db::name('dts_material_'.$category)
        ->field($field)
        ->where($query)
        ->where('material_category_id', $id)
        ->paginate($pagesize, false, ['page' => $page]);

        $this->success('success', $list);
    }

    //物资发放
    public function materialGrant() {

        $letId = $this->request->post('letId');
        $category = $this->request->post('category');
        $receivetime = $this->request->post('receivetime');
        $receiveplace = $this->request->post('receiveplace');

        if(!$letId || !$category) {
            $this->error('请填写物资发放内容');
        }
        if(!in_array($category, $this->categoryArr)) {
            $this->error('物资类型参数有误');
        }
        if($category != 'food') {
            if(!$receivetime || !$receiveplace) {
                $this->error('请填写物资发放内容');
            }
        }
        $result = Db::name('dts_approve_'.$category.'_let')->where('id', $letId)->find();
        if(!$result) {
            $this->error('请选择物资发放');
        }
        $admin = $this->auth->getAdmininfo();

        if($admin['id'] != $result['giveout_id']) {
            $this->error('您没有发放权限');
        }

        __db(function () use ($letId, $category, $receivetime, $receiveplace, $result) {
            $status = 4;
            Db::name('dts_approve_'.$category.'_let')->where('id', $letId)->update(['receivetime' => $receivetime, 'receiveplace' => $receiveplace, 'status' => $status]);
            //待办事项
            $title = __('Approve ' . $category) . '已发放';
            $apiService = new \app\api\controller\Service;
            $apiService->edittodoitem($result['todo_id'], $title, $category, $result['admin_id']);
            $apiService->handletodoitembyapprove($result['id'], $result['giveout_id']);
            //公众号消息
            $thing12 = isset($result['forcause']) ? mb_substr($result['forcause'], 0, 20, 'utf-8') : '';
            $thing16 = Db::name('admin')->where('id', $result['examine_dept_id'])->value('nickname');
            $weChatData2 = ['phrase4' => __('Approve '.$category), 'phrase5' => $title, 'thing12' => $thing12, 'thing16' => $thing16, 'time15' => date("Y-m-d H:i:s", time())];
            $apiService->wechatmessage($result['admin_id'], $apiService->template2, $apiService->jumpUrl($category).'?type=detail&id='.$result['id'], $weChatData2);
        });

        $this->success('success');
    }

    //物资归还
    public function materialReturn() {

        $letId = $this->request->post('letId');
        if(!$letId) {
            $this->error('请选择归还物资');
        }

        __db(function () use ($letId) {
            $list = Db::name('dts_approve_daily_log')->where('daily_let_id', $letId)->select();
            foreach($list as $item) {
                $material = Db::name('dts_material_daily')->where('id', $item['material_daily_id'])->find();
                if($material) {
                    //消耗的
                    $consume = bcsub($material['consume'], $item['quantity']);
                    Db::name('dts_material_daily')->where('id', $material['id'])->update(['consume' => $consume]);
                }
            }
            Db::name('dts_approve_daily_let')->where('id', $letId)->update(['status' => dailyLet::status_7, 'returntime' => date('Y-m-d H:i:s', time())]);
            $admin = $this->auth->getAdmininfo();
            $apiService = new \app\api\controller\Service;
            $todo_id = Db::name('dts_approve_daily_let')->where('id', $letId)->value('todo_id');
            if($todo_id) {
                $apiService->handletodoitem([$todo_id], $admin['id']);
            }
            $apiService->handletodoitembyapprove($letId);
        });

        $this->success('success');
    }

    //物资入库
    public function materialStorage() {

        /**
         * [
         * 'material_id' => '物资Id', 'quantity' => '数量', 'unit_price' => '结算单价（元）', 'shelf_life' => '保质期限', 'saving' => '保存条件:1=常温,2=冷冻,3=冷藏',
         * 'traceability' => '有无产品溯源证明:0=无,1=有', 'qualified' => '有无产品合格证明:0=无,1=有', 'shopping' => '有无购物凭证:0=无,1=有', 
         * 'packaging' => '包装是否完整:0=否,1=是', 'organoleptic' => '感官性状是否正常:0=否,1=是'
         * ]
         */

        $category = $this->request->post('category');
        $params = $this->request->post('params/a');
        if(!$category || !$params) {
            $this->error('请填写物资入库内容');
        }

        if(!in_array($category, $this->categoryArr)) {
            $this->error('物资类型参数有误');
        }
        $voucher_file = $this->request->post('voucher_file');
        $shopping_file = $this->request->post('shopping_file');
        $accept_id = $this->request->post('accept_id');
        if($category == 'food' && !$accept_id) {
            $this->error('验收人参数有误');
        }

        $admin = $this->auth->getAdmininfo();

        __db(function() use($admin, $category, $params, $voucher_file, $shopping_file, $accept_id){
            foreach($params as $item) {
                $material = Db::name('dts_material_'.$category)->where('id', $item['material_id'])->find();
                if(!$material) {
                    ajaxerror('未查询到入库物资');
                }
                //更新库存
                Db::name('dts_material_'.$category)->where('id', $material['id'])->update(['quantity' => $material['quantity'] + $item['quantity']]);
                //入库记录
                $item['category'] = $category;
                $item['voucher_file'] = $voucher_file;
                $item['shopping_file'] = $shopping_file;
                $item['accept_id'] = $accept_id;
                $item['create_id'] = $admin['id'];
                model('model/dts/material/storage/log')->create($item);
            }
        });

        $this->success('success');
    }

    //入库记录
    public function materialStorageLog() {

        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);
        $category = $this->request->get('category');
        if(!in_array($category, $this->categoryArr)) {
            $this->error('物资分类参数有误');
        }
        $type = $this->request->get('type');
        if(!in_array($type, ['storage', 'grant'])) {
            $this->error('查询类型参数有误');
        }

        $list = [];

        if(in_array($type, ['storage'])) {
            $list = Db::name('dts_material_storage_log')->alias('dmsl')
            ->field('dmsl.id,material.name,dmsl.quantity,"storage" as type')
            ->join([
                ['dts_material_'.$category.' material', 'material.id = dmsl.material_id', 'left']
            ])
            ->where('dmsl.category', $category)
            ->paginate($pagesize, false, ['page' => $page]);
        }

        if(in_array($type, ['grant'])) {
            $status = 3;
            $admin = $this->auth->getAdmininfo();
            $list = Db::name('dts_approve_'.$category.'_let')->alias('let')
            ->field('let.id,let.letname as name,(select sum(log.quantity) from fa_dts_approve_'.$category.'_log as log where log.'.$category.'_let_id = let.id) as quantity,"grant" as type')
            ->where(['let.giveout_id' => $admin['id'], 'let.status' => ['>', $status]])
            ->paginate($pagesize, false, ['page' => $page]);
        }

        $this->success('success', $list);
    }

    //记录详情
    public function materialStorageLogDetails() {

        $logId = $this->request->get('logId');
        if(!$logId) {
            $this->error('请选择查询记录');
        }
        $category = $this->request->get('category');
        if(!in_array($category, $this->categoryArr)) {
            $this->error('物资分类参数有误');
        }
        $type = $this->request->get('type');
        if(!in_array($type, ['storage', 'grant'])) {
            $this->error('查询类型参数有误');
        }

        $info = [];

        if(in_array($type, ['storage'])) {
            $info = Db::name('dts_material_storage_log')->alias('dmsl')
            ->field('dmsl.*,material.name as material_name,material.unity,material.specs,accept.nickname as acceptname, create.nickname as createname,FROM_UNIXTIME(dmsl.createtime,"%Y-%m-%d %H:%i") as createtime')
            ->join([
                ['dts_material_'.$category.' material', 'material.id = dmsl.material_id', 'left'],
                ['admin accept', 'accept.id = dmsl.accept_id', 'left'],
                ['admin create', 'create.id = dmsl.create_id', 'left']
            ])
            ->where('dmsl.id', $logId)
            ->find();  
        }
        if(in_array($type, ['grant'])) {
            $info = Db::name('dts_approve_' . $category . '_log')->alias('log')
            ->field('log.*,material.name as materialname')
            ->join('dts_material_'.$category.' material', 'material.id = log.material_'.$category.'_id', 'left')
            ->where('log.'.$category.'_let_id', $logId)
            ->select();
        }

        $this->success('success', $info);
    }
}